<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 17-6-14
 * Time: 上午11:21
 */

namespace console\models\call_rec;


use common\components\tools\Tools;
use League\Flysystem\Adapter\Ftp;
use League\Flysystem\Adapter\Local;
use League\Flysystem\Filesystem;
use League\Flysystem\FilesystemInterface;
use League\Flysystem\MountManager;
use League\Flysystem\Sftp\SftpAdapter;
use yii\base\ErrorException;
use yii\db\Connection;
use yii\helpers\FileHelper;

/**
 * Class SlCallRec
 * @package console\models\call_rec
 *
 * @static MountManager $mountManager
 */
class SlCallRec extends \common\models\credit_public_tables\SlCallRec
{
//    const LINK_TYPE_WC = "http://rec.weice.qiche100.com/main/download?path=";
    const REC_WC= 'WC';
    const REC_HA= 'HA';
    const REC_HB= 'HB';

    /**
     * require League\Flysystem for use
     * @return MountManager
     */
    public static function getMountManager()
    {
        $adapter = new Ftp([
            'host' => \Yii::$app->ftp_call_WC->host,
            'port' => \Yii::$app->ftp_call_WC->port,
            'username' => \Yii::$app->ftp_call_WC->username,
            'password' => \Yii::$app->ftp_call_WC->password,
        ]);
        $ftp_wc = new Filesystem($adapter);
        $adapter = new Ftp([
            'host' => \Yii::$app->ftp_call_WC->host,
            'port' => \Yii::$app->ftp_call_WC->port,
            'username' => \Yii::$app->ftp_call_WC->username,
            'password' => \Yii::$app->ftp_call_WC->password,
        ]);
        $ftp_ha = new Filesystem($adapter);
        $adapter = new Ftp([
            'host' => \Yii::$app->ftp_call_HA->host,
            'port' => \Yii::$app->ftp_call_HA->port,
            'username' => \Yii::$app->ftp_call_HA->username,
            'password' => \Yii::$app->ftp_call_HA->password,
        ]);
        $ftp_hb = new Filesystem($adapter);
        $adapter = new SftpAdapter([
            'host' => \Yii::$app->sftp_99_7->host,
            'port' => \Yii::$app->sftp_99_7->port,
            'username' => \Yii::$app->sftp_99_7->username,
            'password' => \Yii::$app->sftp_99_7->password,
        ]);
        $sftp_99_7 = new Filesystem($adapter);
        $manager = new MountManager();
        $manager->mountFilesystem('ftp_wc', $ftp_wc);
        $manager->mountFilesystem('ftp_ha', $ftp_ha);
        $manager->mountFilesystem('ftp_hb', $ftp_hb);
        $manager->mountFilesystem('sftp_99_7', $sftp_99_7);
        return $manager;
    }

    public static function downloadSourceDirToTarget($source, $s_path, $target, $t_path)
    {
        $manager = self::getMountManager();
        $contents = $manager->listContents("{$source}://{$s_path}", true);
        foreach ($contents as $k => $v) {
            $_type = $v['type'];
            $_path = str_replace($s_path, '', $v['path']);
            $_sftp_path = "{$target}://{$t_path}".$_path;
            $_fs_path = "{$source}://".$v['path'];
            $update = false;
            if ($_type!='dir'){
                if (!$manager->has($_sftp_path)) {
                    $update = true;
                } elseif ($manager->getTimestamp($_fs_path) > $manager->getTimestamp($_sftp_path)) {
                    $update = true;
                }
                if ($update) {
                    $manager->put($_sftp_path, $manager->read($_fs_path));
                }
            }else{
                if (!$manager->has($_sftp_path)){
                    $manager->createDir($_sftp_path);
                }
            }
        }
    }

    /**
     * @param int $t
     * @param \creocoder\flysystem\Filesystem $source
     * @param $s_path
     * @param \creocoder\flysystem\Filesystem $target
     * @param $t_path
     */
    public static function restoreDbAll($t, $source, $s_path, $target, $t_path, $sign_sm, $sign_lg)
    {
        $file_db = $s_path.date("Y-m-d", $t).".db";
        $has = $source->has($file_db);
        if ($has){
            $c = $source->read($file_db);
            $runtime_call_rec_path = \Yii::getAlias("@uploads_root/db/call_rec_{$sign_sm}");
            $_file_db = $runtime_call_rec_path."/".$file_db;
            $dir = dirname($_file_db);
            if (!is_dir($dir)){
                FileHelper::createDirectory($dir);
            }
            if (!file_exists($_file_db)){
                var_dump($dir. " create");
                file_put_contents($_file_db, $c);
            }else{
                var_dump($dir." has");
            }
            $_db = new Connection([
                'dsn' => 'sqlite:'.$_file_db,
            ]);
            $_tr = \Yii::$app->db_public->beginTransaction();
            try{
//                $data = $_db->createCommand("SELECT * FROM {{%VoiceMessage}} WHERE LENGTH (`DTMFA`) >= 11 OR LENGTH (`DTMFB`) >= 11")->queryAll();
                $data = $_db->createCommand("SELECT * FROM {{%VoiceMessage}}")->queryAll();
                $m = new self();
                foreach ($data as $k => $v){
                    $_t = strtotime($v['rstime']);
                    $rec_file = $s_path.basename($v['path']);
                    if ($_m = SlCallRec::findOne([
                        'rec_local' => $sign_lg, //设备
                        'rec_channel' => $v['phyIDA'],//通道号
                        'rec_call' => $v['DTMFA'],//主叫号
                        'rec_called' => $v['DTMFB'],//被叫号
                        'rec_date' => (int)date("Ymd", $_t),
                        'rec_time' => date("H:i:s", $_t),
                        'rec_sec' => $v['longtime'],//持续秒
                        'rec_file' => $t_path.$rec_file,//路径
                    ])){
                        var_dump('has');
                    }else{
                        $_m = clone $m;
                        $_m->rec_local = $sign_lg;//设备
                        $_m->rec_channel = $v['phyIDA'];//通道号
                        $_m->rec_call = $v['DTMFA'];//主叫号
                        $_m->rec_called = $v['DTMFB'];//被叫号
                        $_m->rec_date = (int)date("Ymd", $_t);
                        $_m->rec_time = date("H:i:s", $_t);
                        $_m->rec_sec = $v['longtime'];//持续秒
                        $_m->rec_file = $t_path.$rec_file;//路径
                        if ($_m->save()){
                            var_dump('add');
                        }else{
                            throw new ErrorException(Tools::makeModelGetErrorsToStringAndGetIt($_m), 1011);
                        }
                    }
//                    $update = 0;
//                    if (!$target->has($t_path.$rec_file)) {
//                        $update = 1;
//                    } elseif ($source->getTimestamp($rec_file) > $target->getTimestamp($t_path.$rec_file)) {
//                        $update = 1;
//                    }
//                    if ($update){
//                        $target->put($t_path.$rec_file, $source->read($rec_file));
//                    }
//                    var_dump($rec_file." ".$update);
                }
                $_tr->commit();
            }catch (ErrorException $e){
                $_tr->rollBack();
                throw $e;
            }
        }
    }

    public static function copySourceDirToTarget($date_start, $date_end)
    {
        $s = strtotime($date_start);
        $e = strtotime($date_end);
        for ($d = $s; $d < $e; $d = $d + 86400){
            $_d = date("Ymd", $d);
            self::downloadSourceDirToTarget('ftp_wc', "{$_d}/", 'sftp_99_7', "/Voice/WC/{$_d}/");
            self::downloadSourceDirToTarget('ftp_ha', "{$_d}/", 'sftp_99_7', "/Voice/HA/{$_d}/");
            self::downloadSourceDirToTarget('ftp_hb', "{$_d}/", 'sftp_99_7', "/Voice/HB/{$_d}/");
        }
    }

    /**
     * @param int $t
     * @param \creocoder\flysystem\Filesystem $source
     * @param $s_path
     * @param \creocoder\flysystem\Filesystem $target
     * @param $t_path
     */
    public static function filterStoreDbAndFiles($t, $source, $s_path, $target, $t_path, $sign_sm, $sign_lg)
    {
        $file_db = $s_path.date("Y-m-d", $t).".db";
        $has = $source->has($file_db);
        if ($has){
            $c = $source->read($file_db);
            $runtime_call_rec_path = \Yii::getAlias("@uploads_root/db/call_rec_{$sign_sm}");
            $_file_db = $runtime_call_rec_path."/".$file_db;
            $dir = dirname($_file_db);
            if (!is_dir($dir)){
                FileHelper::createDirectory($dir);
            }
            if (!file_exists($_file_db)){
                var_dump($dir. " create");
                file_put_contents($_file_db, $c);
            }else{
                var_dump($dir." has");
            }
            $_db = new Connection([
                'dsn' => 'sqlite:'.$_file_db,
            ]);
            $_tr = \Yii::$app->db_public->beginTransaction();
            try{
                $data = $_db->createCommand("SELECT * FROM {{%VoiceMessage}} WHERE LENGTH (`DTMFA`) >= 11 OR LENGTH (`DTMFB`) >= 11")->queryAll();
                $m = new self();
                foreach ($data as $k => $v){
                    $_t = strtotime($v['rstime']);
                    $rec_file = $s_path.basename($v['path']);
                    if ($source->has($rec_file)){
                        if ($_m = SlCallRec::findOne([
                            'rec_local' => $sign_lg, //设备
                            'rec_channel' => $v['phyIDA'],//通道号
                            'rec_call' => $v['DTMFA'],//主叫号
                            'rec_called' => $v['DTMFB'],//被叫号
                            'rec_date' => (int)date("Ymd", $_t),
                            'rec_time' => date("H:i:s", $_t),
                            'rec_sec' => $v['longtime'],//持续秒
                            'rec_file' => $t_path.$rec_file,//路径
                        ])){
                            var_dump('has');
                        }else{
                            $_m = clone $m;
                            $_m->rec_local = $sign_lg;//设备
                            $_m->rec_channel = $v['phyIDA'];//通道号
                            $_m->rec_call = $v['DTMFA'];//主叫号
                            $_m->rec_called = $v['DTMFB'];//被叫号
                            $_m->rec_date = (int)date("Ymd", $_t);
                            $_m->rec_time = date("H:i:s", $_t);
                            $_m->rec_sec = $v['longtime'];//持续秒
                            $_m->rec_file = $t_path.$rec_file;//路径
                            if ($_m->save()){
                                var_dump('add');
                            }else{
                                throw new ErrorException(Tools::makeModelGetErrorsToStringAndGetIt($_m), 1011);
                            }
                        }
                        $update = 0;
                        if (!$target->has($t_path.$rec_file)) {
                            $update = 1;
                        } elseif ($source->getTimestamp($rec_file) > $target->getTimestamp($t_path.$rec_file)) {
                            $update = 1;
                        }
                        if ($update){
                            $target->put($t_path.$rec_file, $source->read($rec_file));
                        }
                        var_dump($sign_sm." ".$rec_file." ".$update);
                    }else{
                        var_dump($sign_sm." ".$rec_file." :not found");
                    }
                    echo "\n";
                }
                $_tr->commit();
            }catch (ErrorException $e){
                $_tr->rollBack();
                throw $e;
            }
        }
    }
}